import PropTypes from 'prop-types'
import Taro from '@tarojs/taro'
import { View } from '@tarojs/components'
import classNames from 'classnames'
import AtComponent from '../../common/component'
import AtIcon from '../icon/index'

export default class AtTimeline extends AtComponent {
  handleClick = value => {
    const { onClick } = this.props
    onClick && onClick(value)
  }
  renderItem = data =>
    data.map((item, index) => {
      const { title = '', color, icon, content = [], selected } = item

      const itemRootClassName = classNames({
        'at-timeline-item': true,
        [`at-timeline-item--${color}`]: color,
        'at-timeline-item-selected': selected
      })
      const dotClass = classNames({
        'at-timeline-item__icon': icon,
        'at-timeline-item__dot': !icon
      })
      const iconProps = typeof icon === 'string' ? { type: icon } : icon
      return (
        <View className={itemRootClassName} key={title || index} onClick={() => this.handleClick(item)}>
          <View className='at-timeline-item__tail' />
          {this.renderDot(dotClass, icon, iconProps)}
          {this.renderContent(title, content)}
        </View>
      )
    })
  renderDot = (dotClass, icon, iconProps) => (
    <View className={dotClass}>{icon && <AtIcon {...iconProps} />}</View>
  )
  renderContent = (title, content) => (
    <View className='at-timeline-item__content'>
      <View className='at-timeline-item__content-item'>{title}</View>
      {content.map((sub, subIndex) => (
        <View
          className='at-timeline-item__content-item at-timeline-item__content--sub'
          key={subIndex}
        >
          {sub}
        </View>
      ))}
    </View>
  )
  render() {
    const { pending, data, customStyle, className } = this.props

    const rootClassName = ['at-timeline']
    const rootClassObject = {
      'at-timeline--pending': pending
    }

    return (
      <View className={classNames(rootClassName, rootClassObject, className)} style={customStyle}>
        {this.renderItem(data)}
      </View>
    )
  }
}

AtTimeline.defaultProps = {
  pending: false,
  data: [],
  customStyle: {}
}

AtTimeline.propTypes = {
  pending: PropTypes.bool,
  data: PropTypes.arrayOf(PropTypes.object),
  customStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
  onClick: PropTypes.func
}
